<?php
if(!isset($_SESSION))
session_start();

//This file covers the login and logout procedures.

require_once "db.php"; //Import the database functions


//This function contacts the database to verify the username and password
function check_user_login($user,$pass)
{
	$query = "SELECT username,email,is_admin FROM users WHERE username='$user' AND  password='$pass' LIMIT 1"; //LIMIT 1 is for optimization
	$result = db_query($query); //Note to self: should use MD5 in future 
	if ($result->num_rows == 0) return false; //No users with this combination of username and password is detected
	$row = db_get_row($result); // return the array of the data we are interested in - user , user email,
	return $row;
}

//Error message
function print_wrong_login()
{
	echo "<div class=\"error\">Username or password don't match</div>";
}

//Check if we are trying to logout. See header.php.
if (isset($_GET['logout']))
	session_destroy(); 

//This is the case where the user has pressed Submit and is trying to login
if (isset($_POST['login']))
{
	$row = check_user_login(db_escape($_POST['username']),db_escape($_POST['password'])); //Remember to always escape user input!!! See db.php for details.
	
	if ($row) 
	{
		//Put into the session all user data that we might need
		$_SESSION['uname'] = $row['name'];
		$_SESSION['username'] = $_POST['username'];
		$_SESSION['uisadmin'] = $row['is_admin'];
		$_SESSION['umail'] = $row['email'];
		
		header("Location: index.php");
		exit;
	}
	else print_wrong_login(); //Show an error message;
}

include "header.php";

?>



<!-- LOGIN FORM -->
<!---->
	<div id="login_form">
<form method="post" action="login.php"> 
	<label for="username">Username: </label>
	<input type="text" id="username" name="username"/>
	<br/>
	<label for="pass">Password: </label>
	<input type="password" id="pass" name="password"/>
	<br/>
	<input type="submit" name="login" value="Login"/> 
</form>
</div>
<!--</div>-->
<?php 
// $quercount=" select count(*) from cinemas";
// $rescount = db_query($quercount);
// $r=db_get_row($rescount);
// for($i=1;$i<=$r["count(*)"];$i++){
// 	$query2 = "SELECT * FROM cinemas WHERE  id=$i LIMIT 1"; //LIMIT 1 is for optimization
// 	$result2 = db_query($query2);
// 	$row2= db_get_row($result2);
// 	?>
<!--<a href="saloon.php"><?php echo $row2["name"]; ?></a>&nbsp;&nbsp;-->
<?php
// }
?>